package mz.behaveas.model.expectation {
	import mz.behaveas.model.ducktype.Duck;
	import mz.behaveas.model.ducktype.arraysAreEqual;

	/**
	 * @author maxim.zaks@gmail.com
	 */
	public class EqualExpectation implements Expectation {

		private var _description : String;
		private var behaviour : Function;
		private var equalValue : *;
		private var error : Error = null;
		private var value : *;

		public function EqualExpectation(description : String, behaviour : Function, equalValue : *) {
			this.equalValue = equalValue;
			this.behaviour = behaviour;
			_description = description;
		}

		public function get description() : String {
			return _description;
		}

		public function get isCorrect() : Boolean {
			try {
				value = behaviour();
				if(value is Array && equalValue is Array) {
					return arraysAreEqual(value, equalValue);
				}
				if(equalValue is Duck) {
					return Duck(equalValue).equals(value);
				}
				return value == equalValue;
			} catch(e : Error) {
				error = e;
			}
			return false;
		}

		public function get report() : String {
			if(isCorrect) {
				return FLAG[0] + " The behavioure returned " + equalValue + " as expected.";
			} else {
				if(error != null) {
					return FLAG[1] + " The behavioure was interrupted by: " + error;
				}
			}
			return FLAG[1] + " The behavioure returned " + value + " but " + getEqualValue() + " was expected";
		}

		public function getError() : Error {
			return error;
		}

		private function getEqualValue() : * {
			if(equalValue is Duck) {
				return Duck(equalValue).getReport();
			} else {
				equalValue;
			}
		}
	}
}
